//
//  StockUIV.m
//  mbstore
//
//  Created by Juvid on 14-4-16.
//  Copyright (c) 2014年 huangyi. All rights reserved.
//

#import "StockUIV.h"
#import "StockUIVCell.h"
#import "Fmwk.h"
#import "EPOSDetailEntityResult.h"
#import "EPOSDetailEntity.h"
#import "ItemUI.h"
@interface StockUIV ()

@end

@implementation StockUIV

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
//        mlArrEPOSDetail = [[NSMutableArray alloc] init];
        
#pragma mark henychen 
#pragma mark 读取OrgeCode
         NSString *stock=[[@"media.bundle/stock.json" resourcePath] readString];
        NSData *data = [stock dataUsingEncoding:NSUTF8StringEncoding];
        id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSDictionary * stockdic = (NSDictionary *)json;
        NSDictionary * parsDic = [stockdic objectForKey:@"Pars"];
        
        NSString * OrgCode = [parsDic objectForKey:@"OrgCode"];
        NSUserDefaults * userdefault = [NSUserDefaults standardUserDefaults];
        [userdefault setObject:OrgCode forKey:kOrgCode];
        NSLog(@"+++++++%@",[parsDic objectForKey:@"OrgCode"]);
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIButton *back=[UIButton buttonWithImage:@"back.png"];
    [back addTarget:self action:@selector(OnBack:) forControlEvents:UIControlEventTouchUpInside];
    NSMutableArray *leftItem=[NSMutableArray arrayWithObject:back.barButtonItem];
    [leftItem addObjectsFromArray:self.navigationController.navigationItem.leftBarButtonItems];
    self.navigationItem.leftBarButtonItems=leftItem;
//    self.navigationItem.leftBarButtonItems=self.navigationController.navigationItem.leftBarButtonItems;
    self.navigationItem.rightBarButtonItems=self.navigationController.navigationItem.rightBarButtonItems;
     self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.vieContent.layer setBorderColor:[UIColor lightGrayColor].CGColor];
    [self.vieContent.layer setBorderWidth:1];
//    self.tableView.bounces=NO;
    self.mlStortNum=[[NSMutableArray alloc]init];
    responseCtr=[[CommoditiesController alloc]init];
    startPage=1;
    endPage=10;
    totla=0;
    //    [self GetData];
//    [self ScanBarCodeIntoBillEntity];
    // Do any additional setup after loading the view from its nib.
    
#pragma mark hennychen
    self.mbstoreserver = [[MBStoreSrv alloc] init];
}
-(void)viewWillDisappear:(BOOL)animated{
    mlArrEPOSDetail=nil;
    self.view=nil;
    [SVProgressHUD dismiss];
    totla=-1;
}
#pragma mark 扫描SKU商品（ScanBarCodeIntoBillEntity）
-(void)ScanBarCodeIntoBillEntity:(NSString *)skuid{
    isFinishLoad=YES;
    [SVProgressHUD show];
    
    [responseCtr ScanBarCodeIntoBillEntity:skuid Qty:@"1" ContainerID:@"" IsJudgePrice:@"true" StartNum:startPage EndNum:endPage Success:^(NSDictionary *dicReceiveData) {
        if (mlArrEPOSDetail==Nil) {
            mlArrEPOSDetail=[[NSMutableArray alloc]init];
            colorSnArray = [[NSMutableArray alloc]init];
        }
        //            else{
        [mlArrEPOSDetail addObjectsFromArray:[dicReceiveData objectForKey:@"Message"]];
        NSMutableString * colorsnstring = [[NSMutableString alloc] init];
        for (EPOSDetailEntity * pModel  in mlArrEPOSDetail) {
            NSString * ProdIDstring = pModel.ProdID;
            [colorSnArray addObject:[ProdIDstring substringToIndex:8]];
            [colorsnstring appendString:[NSString stringWithFormat:@"%@|",[ProdIDstring substringToIndex:8]]];
        }
        
#pragma mark 注释
        if (colorSnArray.count > 0) {
            NSLog(@"------%@",colorsnstring);
            photoArray = [[NSMutableArray alloc]init];
            __weak StockUIV * weakSelf = self;
            [self.mbstoreserver SearchTagType:1 CurrentPage:1 PageSize:10 SearchKey:colorsnstring Success:^(NSDictionary *dicReceiveData) {
                //        NSLog(@"RES%@",dicReceiveData);
                NSString * msg = [dicReceiveData objectForKey:@"msg"];
                NSLog(@"%@",msg);
                
                NSArray * rdataArray = [dicReceiveData objectForKey:@"rData"];
                
                for (NSDictionary * prodic in rdataArray) {
                    EPOSProductmodel * productmodel = [EPOSProductmodel getEPOSProductmodelFromDictionary:prodic];
//                    [mlArrEPOSDetail addObject:productmodel];
//                    [photoArray addObject:[NSString stringWithFormat:@"%@--w_40_h_40.jpg",productmodel.mainPhoto]];
                    [photoArray addObject:productmodel];
                }
                
                if (photoArray.count > 0) {
                    for (EPOSProductmodel * productmodel in photoArray) {
                        for (int i = 0; i < [mlArrEPOSDetail count]; i++) {
                            EPOSDetailEntity * pmodel = [mlArrEPOSDetail objectAtIndex:i];
                            if ([productmodel.colorSn isEqualToString:[pmodel.ProdID substringToIndex:8]]) {
                                pmodel.photoimg = [NSString stringWithFormat:@"%@--w_60_h_60.jpg",[productmodel.mainPhoto stringByDeletingPathExtension]];
                                NSLog(@"%@",pmodel.photoimg);
                            }
                        }
                    }
                }
                [weakSelf.tableView reloadData];
                
            } Failure:^(NSError *error) {
                [SVProgressHUD showErrorWithStatus:@"搜索商品失败"];
            }];

        }
        
        [self SearchStock];
        [self.tableView reloadData];
        
    } Failure:^(NSError *error) {
        
    }];

}
-(void)SearchStock{
    if (totla<mlArrEPOSDetail.count&&totla>=0)
    {
        
        EPOSDetailEntity * pModel =  [mlArrEPOSDetail objectAtIndex:totla];
        [responseCtr GetStockJson:pModel.ProdID Success:^(NSDictionary *dicReceiveData) {
            if (dicReceiveData!=nil&&dicReceiveData.count>0) {
                [self.mlStortNum addObject:[dicReceiveData objectForKey:@"HandStock"]];
                [self.tableView reloadData];
                //           判断是否执行每页最后一个库存查询
                if (self.mlStortNum.count==mlArrEPOSDetail.count) {
                    [SVProgressHUD dismiss];
                    isFinishLoad=NO;
                }
                [self SearchStock];
            }
            
        } Failure:^(NSError *error) {
            [SVProgressHUD dismiss];
        }];
        totla++;
    }
    
}

-(void)OnBack:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)setItemId:(NSString *)itemId{
    
}
-(void)setItems:(NSArray *)items{
    
}
#pragma mark 搜索
-(BOOL)textFieldShouldReturn:(UITextField*)theTextField {
    [theTextField resignFirstResponder];
//    [self ReloadSearchData];
    NSLog(@"do something what you want %@",theTextField.text);
    strSearchKey = theTextField.text;
    
    [self ScanBarCodeIntoBillEntity:strSearchKey];

    
    return YES;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return  mlArrEPOSDetail.count;
//    return 14;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifier=@"StockUIVCell";
    StockUIVCell *cell=(StockUIVCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
//        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell=[[[NSBundle mainBundle]loadNibNamed:identifier owner:self options:nil] objectAtIndex:0];
        cell.clipsToBounds=YES;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
    }
    else{
        while ([cell.contentView.subviews lastObject] != nil)
        {
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
        
    }
    
//    EPOSProductmodel * pModel =  [mlArrEPOSDetail objectAtIndex:indexPath.row];
//    [cell.imgStock setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@--w_40_h_40.jpg",pModel.mainPhoto]]];
//    
//    cell.labNum.text = [NSString stringWithFormat:@"产品编号:%@",pModel.colorSn];
//    cell.labName.text = pModel.goodsName;

    EPOSDetailEntity * pModel =  [mlArrEPOSDetail objectAtIndex:indexPath.row];
    [cell.imgStock setImageWithURL:[NSURL URLWithString:pModel.photoimg]];
    cell.labNum.text = pModel.ProdID;
    cell.labName.text = pModel.ProdName;
    cell.labColor.text = pModel.ColorName;
    cell.labSize.text = pModel.SizeName;
    cell.labYear.text = pModel.ProdYear;
    //    判断当前库存是否获取，获取到赋值
//    if (self.mlStortNum.count>indexPath.row) {
//        cell.labStockNum.text=[NSString stringWithFormat:@"%@",[self.mlStortNum objectAtIndex:indexPath.row]];
//    }
       //    cell.textLabel.text=@"fslkahgl";
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    EPOSDetailEntity * pModel =  [mlArrEPOSDetail objectAtIndex:indexPath.row];
    ItemUI * itemui = [[ItemUI alloc] initWithNibName:@"ItemUI" bundle:nil];
    itemui.tagType = 1;
    itemui.productId = [pModel.ProdID substringToIndex:8];
    
    [self.navigationController pushViewController:itemui animated:YES];
    NSLog(@"-----%@",pModel.ProdID);
}
//重新初始化搜索参数
-(void)ReloadSearchData{
    startPage=1;
    endPage=21;
    catID=0;
    tagType=1;
    
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    
    PrevCGPoint=scrollView.contentOffset;
    if (PrevCGPoint.y>scrollView.contentSize.height-scrollView.frame.size.height) {
        if (endPage<100&&mlArrEPOSDetail.count%10==0) {
            if (isFinishLoad) return;
            startPage+=10;
            endPage=startPage+9;
            [self ScanBarCodeIntoBillEntity:strSearchKey];
        }
        
    }
    
}
-(void)GetData{
    isFinishLoad=YES;
     __weak StockUIV * weakSelf = self;
    [self.mbstoreserver SearchTagType:tagType
                   CurrentPage:startPage
                      PageSize:endPage
                         CatID:catID
                     SearchKey:strSearchKey
                       Success:^(NSDictionary *dicReceiveData) {
                           NSString * msg = [dicReceiveData objectForKey:@"msg"];
                           NSLog(@"%@",msg);
                           NSDictionary * pagesdic = [dicReceiveData objectForKey:@"pages"];
                           NSNumber * totalcount = [pagesdic objectForKey:@"total_count"];
                           total_count = [totalcount intValue];
                           NSArray * rdataArray = [dicReceiveData objectForKey:@"rData"];
                           
                           for (NSDictionary * prodic in rdataArray) {
                               EPOSProductmodel * productmodel = [EPOSProductmodel getEPOSProductmodelFromDictionary:prodic];
                               [mlArrEPOSDetail addObject:productmodel];
                           }
                           [weakSelf.tableView reloadData];


                           isFinishLoad=NO;
                       } Failure:^(NSError *error) {
                           isFinishLoad=NO;
                       }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
